<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '创建文化定制活动',
  },
}
</route>

<script setup>
import CustomApi from '@/service/custom'
import dayjs from 'dayjs'
import { uploadUrl } from '@/service/common'
import { useSelectedProgrammeStore } from '@/store/selectedProgramme'
import { isValidPhone, prevPageNeedRefresh, uniNavigateTo } from '@/utils'
import { useDictStore } from '@/store/dict'
import { MAX_PROGRAMME_COUNT } from '@/configs/constant'
import { getProgrammeCategory } from '@/service/dict'
import BasePopup from '@/components/BasePopup.vue'

const dictStore = useDictStore()
const categoryList = computed(() => dictStore.dictData.jointActivityCategory)

const _selectedProgrammeList = computed(() => {
  const sList = useSelectedProgrammeStore().selectedProgrammeList
  if (sList.length) {
    return sList.map((item) => item.id)
  }
  return []
})

/** --------- 类型 start ---------- */
const categoryState = reactive({
  visible: false,
  currentValue: '',
  currentLabel: '',
  columns: [],
})
const getCategoryList = async () => {
  const { code, result } = await getProgrammeCategory()
  if (code === 200 && result) {
    categoryState.columns = result
  }
}
getCategoryList()
const checkCategory = (child) => {
  if (child) {
    categoryState.currentValue = child.id
    categoryState.currentLabel = child.label
  }
  categoryState.visible = false
}
/** --------- 类型 end ---------- */

/** 上传 start */
const fileState = reactive({
  coverList: [],
})
const changeCoverUpload = ({ fileList }) => {
  fileState.coverList = fileList
  console.log('fileState.coverList', fileState.coverList)
}
/** 上传 end */

const nowDate = new Date().getTime()

const formRef = ref()
const formModel = ref({
  name: '', // 活动名称
  category: '', // 活动类型
  startTime: nowDate, // 开始时间
  duration: '', // 活动时长
  playerNumber: '', // 参与人数
  contactor: '', // 联系人
  contactPhone: '', // 联系电话
  remark: '', // 活动介绍
  coverUrl: '', // 活动封面
  programs: '', // 节目
})
const formKeyMap = {
  name: '活动名称',
  category: '活动类型',
  startTime: '开始时间',
  duration: '活动时长',
  playerNumber: '参与人数',
  contactor: '联系人',
  contactPhone: '联系电话',
  remark: '活动介绍',
  coverUrl: '封面图',
}

const submitForm = () => {
  if (categoryState.currentValue) {
    formModel.value.category = categoryState.currentValue
  }
  if (fileState.coverList.length > 0) {
    const urlArr = fileState.coverList.map((item) => {
      const res = JSON.parse(item.response)
      return res?.message
    })
    formModel.value.coverUrl = urlArr.join(',')
  }
  let objKey = ''
  for (const key in formKeyMap) {
    if (!formModel.value[key]) {
      objKey = key
      break
    }
  }
  if (objKey) {
    uni.showToast({
      title: `${formKeyMap[objKey]}不能为空`,
      icon: 'none',
    })
    return false
  }
  // 判断手机号是否正确
  if (!isValidPhone(formModel.value.contactPhone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
    })
    return false
  }

  formRef.value
    .validate()
    .then(async () => {
      formModel.value.programs = _selectedProgrammeList.value.join(',')
      const startTime = dayjs(formModel.value.startTime).format(
        'YYYY-MM-DD HH:mm:ss',
      )
      const params = { ...formModel.value, startTime }
      const apiFn = CustomApi.createLevelActivity
      const { code, result, message } = await apiFn(params)
      if (code === 200 && result) {
        const title = '创建成功'
        uni.showToast({
          icon: 'success',
          title,
        })
        setTimeout(() => {
          isNavigateBack.value = true
          uni.navigateBack()
        }, 1000)
      } else {
        uni.showToast({
          icon: 'error',
          title: message,
        })
      }
    })
    .catch((error) => {
      console.error(error)
    })
}

onBeforeUnmount(() => {
  useSelectedProgrammeStore().clearSelectedProgrammeList()
})

const isNavigateBack = ref(false)
onUnload(() => {
  prevPageNeedRefresh(isNavigateBack.value)
})
</script>

<template>
  <view class="common-page-bg">
    <view class="p-24rpx pb-60rpx">
      <wd-form
        custom-class="common-form"
        ref="formRef"
        :model="formModel"
      >
        <wd-cell-group>
          <wd-input
            label="活动名称"
            label-width="80px"
            prop="name"
            v-model="formModel.name"
            placeholder="请输入"
          />
          <!-- <wd-picker
            :columns="categoryList"
            label="活动类型"
            v-model="formModel.category"
          /> -->
          <wd-cell
            title="节目类型"
            custom-class="flex-cell"
          >
            <view
              class="wd-cell__right flex items-center justify-end"
              :class="
                categoryState.currentLabel ? '' : 'wd-picker__cell--placeholder'
              "
              @click="categoryState.visible = true"
            >
              <view class="wd-cell__value">
                {{ categoryState.currentLabel || '请选择' }}
              </view>
              <wd-icon
                name="arrow-right"
                size="32rpx"
                color="rgba(0, 0, 0, 0.25)"
              ></wd-icon>
            </view>
          </wd-cell>
          <wd-datetime-picker
            label="开始时间"
            type="date"
            v-model="formModel.startTime"
          />
          <wd-input
            type="digit"
            label="活动时长(分钟)"
            label-width="100px"
            prop="duration"
            v-model="formModel.duration"
            placeholder="请输入"
          />
          <wd-input
            type="digit"
            label="参与人数"
            label-width="80px"
            prop="playerNumber"
            v-model="formModel.playerNumber"
            placeholder="请输入"
          />
          <wd-input
            label="联系人"
            label-width="80px"
            prop="contactor"
            v-model="formModel.contactor"
            placeholder="请输入"
          />
          <wd-input
            type="digit"
            label="联系电话"
            :maxlength="11"
            label-width="80px"
            prop="contactPhone"
            v-model="formModel.contactPhone"
            placeholder="请输入"
          />
          <wd-cell title="活动介绍">
            <wd-textarea
              v-model="formModel.remark"
              placeholder="请输入"
            />
          </wd-cell>
          <wd-cell
            title="封面图"
            label-width="80px"
          >
            <wd-upload
              :file-list="fileState.coverList"
              :limit="1"
              :action="uploadUrl"
              image-mode="aspectFill"
              @change="changeCoverUpload"
            ></wd-upload>
          </wd-cell>
          <wd-cell
            custom-class="flex-cell"
            title="选择节目"
          >
            <view
              class="flex items-center justify-end"
              @click="uniNavigateTo('/pages-sub/programme/chose/index')"
            >
              <text class="mr-16rpx">
                已选 {{ _selectedProgrammeList.length }}/{{
                  MAX_PROGRAMME_COUNT
                }}
              </text>
              <wd-icon
                name="arrow-right"
                size="32rpx"
                color="rgba(0, 0, 0, 0.25)"
              ></wd-icon>
            </view>
          </wd-cell>
        </wd-cell-group>
      </wd-form>
      <wd-button
        custom-class="submit-btn"
        type="primary"
        @click="submitForm"
        :round="false"
        block
      >
        提交
      </wd-button>
    </view>

    <!-- 类型弹窗 -->
    <BasePopup
      v-model:visible="categoryState.visible"
      title="请选择"
    >
      <view class="category-group">
        <view
          v-for="item in categoryState.columns"
          :key="item.id"
          class="category-item"
        >
          <view class="category-item-title">{{ item.label }}</view>
          <view
            v-if="item.children?.length"
            class="flex flex-wrap"
          >
            <view
              v-for="child in item.children"
              :key="child.id"
              class="category-item-child"
              :class="{ active: categoryState.currentValue === child.id }"
              @click="checkCategory(child)"
            >
              {{ child.label }}
            </view>
          </view>
        </view>
      </view>
    </BasePopup>
  </view>
</template>

<style lang="scss">
@import '../../../style/common-form.scss';

.category-group {
  padding: 32rpx;
  max-height: 50vh;
  overflow-y: auto;

  .category-item {
    margin-bottom: 16rpx;

    &-title {
      position: relative;
      padding-left: 24rpx;
      margin-bottom: 16rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: $uni-text-color;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 32rpx;
        background-image: linear-gradient(169deg, #67bdf6 0%, #2c84db 100%);
        border-radius: 2rpx;
      }
    }

    &-child {
      min-width: 180rpx;
      padding: 12rpx;
      margin: 0 16rpx 16rpx 0;
      font-size: 26rpx;
      color: $uni-text-color-grey;
      text-align: center;
      background: #f4f7fc;
      box-sizing: border-box;
      border-radius: 8rpx;

      &.active {
        background: rgba(249, 143, 24, 0.2);
        color: #f98f18;
      }
    }
  }
}
</style>
